using System;
using System.Configuration;
using System.Data.SqlClient;
using Destra.Common.Services;

namespace Destra.Common.DataAccess
{
    public abstract class DACBase : IDisposable
    {
        private SqlConnection m_connection;

        virtual protected string ConnectionStringName
        {
            get
            {
                ServiceConfiguration serviceConfiguration = (ServiceConfiguration)ConfigurationManager.GetSection("Destra.Services");

                return serviceConfiguration.ConnectionStringName;
            }
        }

        public virtual SqlConnection Connection
        {
            get
            {
                if (m_connection == null)
                {
                    if (ConfigurationManager.ConnectionStrings[this.ConnectionStringName] == null)
                    {
                        throw new ApplicationException(
                            string.Format(
                                "Could not find connection string '{0}'",
                                this.ConnectionStringName));
                    }

                    m_connection = new SqlConnection(
                        ConfigurationManager.ConnectionStrings[this.ConnectionStringName].ConnectionString);
										
                    m_connection.Open();
                }

                return m_connection;
            }
        }

        void IDisposable.Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (m_connection != null)
                {
                    m_connection.Close();
                    m_connection.Dispose();
                    m_connection = null;
                }
            }
        }
    }
}